using Microsoft.EntityFrameworkCore;
using Traceability.Infrastructure;
using MediatR;
using System.Reflection;
using Traceability.Domain;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Text;
using Traceability.API.Services;
using Traceability.API.Extensions;

using Microsoft.Extensions.FileProviders;
using Microsoft.AspNetCore.Http.Features;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo 
    { 
        Title = "可追溯性API", 
        Version = "v1",
        Description = "可追溯性系统的API接口文档",
        Contact = new OpenApiContact
        {
            Name = "开发团队",
            Email = "dev@traceability.com"
        }
    });

    // 配置XML文档路径
    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    if (File.Exists(xmlPath))
    {
        c.IncludeXmlComments(xmlPath);
    }

    // 显示 授权信息
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
    {
        Description = "请输入JWT授权Token，Bearer Token值",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        BearerFormat = "JWT",
        Scheme = "Bearer"
    });
    c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new string[]
            {

            }
        }
    });
});

builder.Services.AddDbContext<MyDbContext>(x => x.UseSqlServer(builder.Configuration.GetConnectionString("Conn")));
//授权认证使用JWT
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
{
    // 私钥
    var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
    o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
    {
        // 验证颁发者
        ValidateIssuer = true,
        // 颁发者信息
        ValidIssuer = "BeiJingBW",

        // 验证订阅者
        ValidateAudience = true,
        // 订阅者
        ValidAudience = "BeiJingBW",

        // 验证是否过期
        ValidateLifetime = true,

        // 验证私钥
        IssuerSigningKey = new SymmetricSecurityKey(secretByte)

    };
});

// Add MediatR
builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));

// Add repositories
builder.Services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
builder.Services.AddScoped<IBaseRepository<User>, BaseRepository<User>>();
builder.Services.AddScoped<IBaseRepository<Role>, BaseRepository<Role>>();
builder.Services.AddScoped<IBaseRepository<UserRole>, BaseRepository<UserRole>>();
builder.Services.AddScoped<IBaseRepository<Products>, BaseRepository<Products>>();
builder.Services.AddScoped<IBaseRepository<TraceabilityInfo>, BaseRepository<TraceabilityInfo>>();

// Add JWT Service
builder.Services.AddScoped<JwtService>();

// Add Redis Service
builder.Services.AddSingleton<RedisService>();
builder.Services.AddScoped<TraceabilityRedisHelper>();
builder.Services.AddScoped<RedisCaptchaService>();


// Add Captcha Services
builder.Services.AddSingleton<CaptchaService>();
builder.Services.AddSingleton<MemoryCaptchaService>();
builder.Services.AddScoped<HybridCaptchaService>();

// Add QiNiu Service
builder.Services.AddQiNiuService(builder.Configuration);

// Configure form options for file uploads
builder.Services.Configure<FormOptions>(options =>
{
    // 设置请求体最大大小为50MB
    options.MultipartBodyLengthLimit = 52428800; // 50MB
    options.ValueLengthLimit = 52428800; // 50MB
});

// Add CORS
builder.Services.AddCors(options =>
{
    options.AddPolicy("CorsPolicy", policy =>
    {
        policy.AllowAnyOrigin()
              .AllowAnyMethod()
              .AllowAnyHeader();
    });
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseStaticFiles(); // 默认的wwwroot静态文件

// 确保uploads目录存在
var uploadsPath = Path.Combine(builder.Environment.ContentRootPath, "uploads");
if (!Directory.Exists(uploadsPath))
{
    Directory.CreateDirectory(uploadsPath);
}

var imagesPath = Path.Combine(uploadsPath, "images");
if (!Directory.Exists(imagesPath))
{
    Directory.CreateDirectory(imagesPath);
}

// 配置uploads文件夹的静态文件访问
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(uploadsPath),
    RequestPath = "/uploads"
});

app.UseCors("CorsPolicy");

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();
